﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyRobot : Enemy
{
	#region 成员变量

	public Transform tr1, tr2;    // 在两个位置之前来回走动
	LineRenderer line;
	EnemyBullet bullet;
	public float lineLength;
	Vector3 t1, t2;
	Vector3 dir;    // 向量t1t2
	int isRev = 1; // 是否向右移动
	public float moveSpeed = 5;
	private float tmpSpeed;
	#endregion

	#region 生命周期函数
	protected override void Start() {
		base.Start();
		tmpSpeed = moveSpeed;       // 记录初始速度
		bullet = transform.Find("line").GetComponent<EnemyBullet>();
		line = transform.Find("line").GetComponent<LineRenderer>();
		SetIniAttributes(8, 8, 3, EnemyType.EnemyRobot);
		bullet.SetIniAttributes(this);
		t1 = tr1.position;
		t2 = tr2.position;
		dir = (t2 - t1).normalized;
	}

	private void Update() {

		if (allowMove) transform.Translate(dir * Time.deltaTime * moveSpeed * isRev);

		// 两点之前来回巡逻
		Vector3 v1 = t1 - transform.position;
		Vector3 v2 = t2 - transform.position;
		if (Vector3.Angle(v1, v2) <= 30) {    // 向量夹角小于30度, 需要改变方向
			isRev = Vector3.Distance(Vector3.zero, v1) < Vector3.Distance(Vector3.zero, v2) ? 1 : -1;
			StartCoroutine(IOutAttack(2));
		}
	}

	#endregion


	#region 重写暂停与继续

	public override void OnPauseAni() {
		base.OnPauseAni();
		timeSpan = Time.realtimeSinceStartup - timePrev;    // 先记下时间
		isPause++;
		moveSpeed = 0;                                      // 后暂停
	}

	public override void OnContinueAni() {
		base.OnContinueAni();
		moveSpeed = tmpSpeed;
	}
	#endregion


	/// <summary>
	/// 在v1, v2两点之间来回移动位置
	/// </summary>
	/// <param name="v1"></param>
	/// <param name="v2"></param>
	private void SHMOnUpdate(Vector3 v1, Vector3 v2) {

	}

	#region 机器人发射与关闭激光武器
	private void ShowLine() {
		line.gameObject.SetActive(true);
		line.enabled = true;
		line.startWidth = 0.1f;
		// line.endWidth = 0.1f;
		line.SetPosition(0, Vector3.zero + new Vector3(0, 0.2f, -1));
		line.SetPosition(1, dir * lineLength + new Vector3(0, 0.2f, -1));
	}


	private void HideLine() {
		line.enabled = false;
	}

	private float timePrev = 0;
	private float timeSpan;
	private int isPause = 0;    // 用整型变量好于直接用moveSpeed判断
	public IEnumerator IOutAttack(float time) {
		ShowLine();
		SetEnemyState(EnemyState.Shoot, true);
		timePrev = Time.realtimeSinceStartup;

		yield return new WaitForSeconds(time);      // 可能在快速点击暂停和继续键时, 激光并没有显示time长度的时间, 但是再快很难两秒内超过连续两次

		while (isPause > 0) {           // 按了暂停键, 不能用moveSpeed == 0直接判断
			yield return null;
			if (moveSpeed > 0) {        // 按了继续键
				yield return new WaitForSeconds(Mathf.Max(0, time - timeSpan));       // 等待剩余时间
				break;
			}
		}

		SetEnemyState(EnemyState.Shoot, false);
		HideLine();
		isPause = 0;    // 执行完关闭激光, isPause才等于0
	}
	#endregion
}
